package cn.admin.configcenter.registry.service;

import cn.admin.configcenter.registry.common.config.ConfigSetting;
import cn.admin.remoting.Connection;
import cn.admin.remoting.impl.DefaultConnection;
import cn.admin.remoting.impl.LCL_AliveSessionsListener;

import java.util.Iterator;
import java.util.concurrent.Executor;

public class ServerUtil {

    private static Executor threadPool;

    public static Executor getConfigServerTP() {
        return threadPool;
    }

    public static void setConfigServerTP(Executor executor) {
        threadPool = executor;
    }

    public static String selfServerIp() {
        return ConfigSetting.serverIp;
    }

    public static String getIp(String hostId) {
        int idx = hostId.indexOf(58);
        return idx >= 0 ? hostId.substring(0, idx) : hostId;
    }

    public static Connection getIncomingConn(String fromIp) {
        Iterator<DefaultConnection> it = LCL_AliveSessionsListener.
                aliveSessions().iterator();

        Connection connection;
        do {
            if (!it.hasNext()) {
                return null;
            }

            connection = it.next();
        } while (!connection.getRemoteAddress().equals(fromIp)
                || connection.getLocalPort() != 9600);

        return connection;
    }

}
